﻿using IdentityModel.Client;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace Client2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var str = GetToken().Result;
            // var str = $@"eyJhbGciOiJSUzI1NiIsImtpZCI6IjgwOTE0OThDNDEyNDA1MTNENDE4OUYyQjUzODBGRDYyIiwidHlwIjoiYXQrand0In0.eyJuYmYiOjE1OTk5MTE3NjgsImV4cCI6MTU5OTkxNTM2OCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo2NDY2NyIsImNsaWVudF9pZCI6ImNsaWVudCIsImp0aSI6IjhCRUNFQUIzNUNDREU2MDIzNjMxQkY0RDVBNzE1OUZBIiwiaWF0IjoxNTk5OTExNzY4LCJzY29wZSI6WyJhcGkxIl19.asUsCDFFSi74Go-ouccnlf6lOi2-g5hI7KqrdkuKeRp9A8cR514-bFEWX_L0uP5Kp_la_1tbGKLHrIAf5tsOBdRv9sRRvxl9BTm9w05xKzwK-AiMoamUK-H6fPxSOitK9PFODI7A92q5KI3ne0_VEb5Z7adq7nSOnC69hbT1QeT72tQnBxrZmwHYJSqNgb_vXqtYahcRGcWkbs2KlvmLcoqs453rnp6rU6rxI1ZJPrWo5ty5-Hk0Q-0Il47DrT05nE8nI9qcaeDVZy23a-6Oi2dNCFHy0SdM2C2hH25Rw32EYiEciyr_17Zsqsh5zSWay5wrCXgdqkW5_7dZENdCeA";
            Console.WriteLine(str);
            var client = new HttpClient();
            Console.WriteLine("---------------调用普通接口------------------");
            var get = client.GetAsync("http://localhost:52250/WeatherForecast/get").Result.Content.ReadAsStringAsync().Result;
            Console.WriteLine($@"----{get}------");


            Console.WriteLine("---------------调用需要授权接口------------------");

            client.SetBearerToken(str);
            var getauth =  client.GetAsync("http://localhost:52250/WeatherForecast/getauth").Result;

            if (getauth.IsSuccessStatusCode)
            {
                //.Result.Content.ReadAsStringAsync().Result;
                Console.WriteLine($@"----{getauth.Content.ReadAsStringAsync().Result}------");
            } 
            else
            {
                Console.WriteLine($@"----错误{getauth.StatusCode}------");
            }


            Console.WriteLine("-----------------------------------------");


        }

        private static async Task<string> GetToken()
        {
            var client = new HttpClient();
            var disco = await client.GetDiscoveryDocumentAsync("http://localhost:64667");
            if (disco.IsError)
            {
                return disco.Error;
            }
            var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = disco.TokenEndpoint,
                ClientId = "client",
                ClientSecret = "secret",
                Scope = "api1"
            });

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return tokenResponse.ErrorDescription;
            }
            return tokenResponse.AccessToken;
        }
    }
}
